package com.defysoft.waukidsschool.scanmode;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukidsschool.BaseActivity;
import com.defysoft.waukidsschool.Data_Type.CheckStudent;
import com.defysoft.waukidsschool.JsonParser;
import com.defysoft.waukidsschool.R;
import com.defysoft.waukidsschool.Sqlite_Connect;
import com.defysoft.waukidsschool.Wake_Screen;
import com.defysoft.waukidsschool.main.Main_Intro;

public class Scanmode_StartScan extends BaseActivity {

	Toolbar toolbar;
	Calendar calendar;
	String date;
	String nowdate;
	Thread subThread;
	ArrayList<CheckStudent> list; // 유치원 원생리스트
	ArrayList<String> alwaysdata;// 블루투스스캔 값얻어오는리스트
	ArrayList<String> sendlist; // 등원 체크된원생 리스트
	ArrayList<String> endlist; // 하원 원생 채크
	ArrayList<String> getuuid; // 테스트 스캔 리스트
	private SharedPreferences login_code;
	private SharedPreferences log_data;
	private SharedPreferences.Editor editor;
	SharedPreferences settingtime;
	SharedPreferences restarttime;
	GridView gridView;
	ImageView stop;
	TextView updatebtn;
	ScanAdapter scanAdapter;
	private Handler mHandler;
	boolean upattend = true;
	boolean onoff = true;
	boolean checkattend = false;
	int checkmode = 0;
	int checkback = 0;
	TextView title;
	TextView testscan = null;
	Sqlite_Connect sc;
	int checklimit = 4; // 귀가채크횟수+1
	String codea = null;
	String codeb = null;
	int checkscancount = 0;
	boolean nowversion = true;
	Runnable runnable;
	Cursor savelog;
	int scancount = 0;

	private long SCAN_PERIOD = 10000;

	private BluetoothAdapter mBluetoothAdapter;

	final int SUCCESS = 10;
	final int FIRSTSUCCESS = 7;
	final int TWOSUCCESS = 6;
	final int THREESUCCESS = 5;
	final int FAIR = 8;
	private static final int REQUEST_ENABLE_BT = 3;
	int settime[] = new int[4];
	private static final String TAG = "Sample_3";
	private static PowerManager.WakeLock sCpuWakeLock;

	RelativeLayout RL;
	TextView err;
	TextView normal;
	TextView close;
	ListView log;
	LogAdapter logAdapter;
	ArrayList<String> loglist;
	Cursor cursor;

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		if (checkback == 0) {
			stop.callOnClick();
		} else {
			Wake_Screen.releaseCpuLock();
			super.finish();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		onoff = false;
		setList();
		checkback = 1;
		scanLeDevice(false);
		moveTaskToBack(true);
		finish();
		ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		am.restartPackage(getPackageName());
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.i("ddd", getPackageResourcePath());
		setContentView(R.layout.activity_scanmode__start_scan);
		setStartData();
		setstartLog();
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		try {
			SCAN_PERIOD = (Integer.parseInt(getIntent()
					.getStringExtra("second")) * 1000);
		} catch (Exception e) {
			SCAN_PERIOD = 1000;
		}

		try {
			if (getIntent().getStringExtra("checklimit") != null) {
				checklimit = (Integer.parseInt(getIntent().getStringExtra(
						"checklimit"))) + 1;
			} else {
				checklimit = 4;
			}
		} catch (Exception e) {
			checklimit = 4;
		}
		upattend = true;
		onoff = true;
		checkattend = false;
		checkmode = 0;
		checkback = 0;
		sendlist = new ArrayList<String>();
		mHandler = new Handler();
		calendar = Calendar.getInstance();
		date = calendar.get(Calendar.YEAR) + "."
				+ (calendar.get(Calendar.MONTH) + 1) + "."
				+ calendar.get(Calendar.DAY_OF_WEEK);
		nowdate = calendar.get(Calendar.YEAR) + "."
				+ (calendar.get(Calendar.MONTH) + 1) + "."
				+ calendar.get(Calendar.DAY_OF_WEEK);
		settingtime = getSharedPreferences("settingtime", MODE_PRIVATE);
		updatebtn = (TextView) findViewById(R.id.STARTSCAN_UPDATE);
		updatebtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onoff = false;
				setList();
				checkback = 1;
				scanLeDevice(false);
				startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse("market://details?id=" + getPackageName())));
				finish();
			}
		});
		log_data = getSharedPreferences("log_data", MODE_PRIVATE);
		editor = log_data.edit();
		sc = new Sqlite_Connect(this);
		alwaysdata = new ArrayList<String>();
		gridView = (GridView) findViewById(R.id.STARTSCAN_GRID);
		stop = (ImageView) findViewById(R.id.STARTSCAN_STOP);
		login_code = getSharedPreferences("login_code", MODE_PRIVATE);
		// testscan=(TextView)findViewById(R.id.STARTSCAN_TESTSCAN);
		toolbar = (Toolbar) findViewById(R.id.STARTSCAN_TOOL);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		stop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(
						Scanmode_StartScan.this);
				builder.setMessage("종료하시면 자동 실행모드도 종료됩니다. 정말로 종료 하시겠습니까?")
						.setCancelable(false)
						.setPositiveButton("종료",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Intent intent = new Intent(
												Scanmode_StartScan.this,
												Main_Intro.class).putExtra(
												"AUTOSTART", 1);
										PendingIntent pendingIntent = PendingIntent
												.getActivity(
														Scanmode_StartScan.this,
														12345,
														intent,
														PendingIntent.FLAG_CANCEL_CURRENT);
										AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
										am.cancel(pendingIntent);
										onoff = false;
										setList();
										checkback = 1;
										scanLeDevice(false);
									}
								})
						.setNegativeButton("취소",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});
		settime[0] = Integer.parseInt(settingtime.getString("STARTGO", "0"));
		settime[1] = Integer.parseInt(settingtime.getString("STARTBACK", "0"));
		settime[2] = Integer.parseInt(settingtime.getString("ENDGO", "0"));
		settime[3] = Integer.parseInt(settingtime.getString("ENDBACK", "0"));

		title = (TextView) findViewById(R.id.STARTSCAN_TITLE);
		final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();
		if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		} else {
			startThread(1);
		}
	}

	public void setstartLog() {
		RL = (RelativeLayout) findViewById(R.id.SCHOOL_SCAN_RL);
		err = (TextView) findViewById(R.id.SCHOOL_SCAN_LOG_ERR);
		log = (ListView) findViewById(R.id.SCHOOL_SCAN_LOG);
		loglist = new ArrayList<String>();
		logAdapter = new LogAdapter();
		log.setAdapter(logAdapter);
		normal = (TextView) findViewById(R.id.SCHOOL_SCAN_LOG_NORMAR);
		close = (TextView) findViewById(R.id.SCHOOL_SCAN_LOG_EXIT);
		normal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loglist = new ArrayList<String>();
				if (cursor != null) {
					cursor.close();
				}
				cursor = sc.check_School();
				while (cursor.moveToNext()) {
					loglist.add(cursor.getString(0)
							+ (cursor.getInt(2) % 2 == 1 ? "  # " : "  @ ")
							+ cursor.getString(1));
				}
				logAdapter.notifyDataSetChanged();
				RL.setVisibility(View.VISIBLE);
			}
		});
		err.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loglist = new ArrayList<String>();
				if (cursor != null) {
					cursor.close();
				}
				cursor = sc.check_School(1);
				while (cursor.moveToNext()) {
					loglist.add(cursor.getString(0) + "  # "
							+ cursor.getString(1));
				}
				logAdapter.notifyDataSetChanged();
				RL.setVisibility(View.VISIBLE);
			}
		});
		close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				RL.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case 1:
					mainThread();
					break;
				case 2:
					firstThread();
					break;
				case 3:
					twoThread();
					break;
				case 4:
					threeThread();
					break;
				}
			}
		});
		firstThread.start();
		if (choice == 1) {
			startDIal();
		}
	}

	public void subThread(int choice, String code) {
		final int cho = choice;
		final String cd = code;
		subThread = new Thread(new Runnable() {

			@Override
			public void run() {
				switch (cho) {
				case 1:
					try {
						JSONObject jsonObject = new JSONObject(
								publicHttpCallback(HTTP_SEND_START, "code="
										+ cd));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				case 2:
					try {
						JSONObject jsonObject = new JSONObject(
								publicHttpCallback(HTTP_SEND_END, "code=" + cd));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				}
			}
		});
		subThread.start();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {// ���������������üũ

		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) { // ������� ������
				// Bluetooth is now enabled, so set up a chat session
				Toast.makeText(this, "블루투스 사용가능", Toast.LENGTH_LONG).show();
				startThread(1);
			} else { // ������� ������ ���� �����佺Ʈ ���� ��
				// User did not enable Bluetooth or an error occurred
				Toast.makeText(this, "블루투스 사용불가", Toast.LENGTH_LONG).show();
				finish();
			}
		}
	}

	private void scanLeDevice(final boolean enable) {

		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mHandler.removeCallbacks(runnable);
			
			runnable=new Runnable() {
					@Override
					public void run() {
						checkscancount++;
						mBluetoothAdapter.stopLeScan(mLeScanCallback);
						if (onoff) {
							setCheckMode();
							startThread(checkmode);
						}
					}
				};
			mHandler.postDelayed(runnable, SCAN_PERIOD);
			alwaysdata = new ArrayList<String>();
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}

	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			final int rss = rssi;
			final byte[] scan = scanRecord;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					boolean checktype = true;
					for (int i = 0; i < list.size(); i++) {
						if (list.get(i).bea_id.equals(device.getAddress())) {
							list.get(i).rssi = rss + "";
							for (int j = 0; j < alwaysdata.size(); j++) {
								if (alwaysdata.get(j).equals(
										device.getAddress())) {
									checktype = false;
									break;
								}
							}
							if (checktype) {
								alwaysdata.add(device.getAddress());
							}
							break;

						}
					}

				}
			});
		}
	};

	private void testScanLeDevice(final boolean enable) {
		getuuid = new ArrayList<String>();
		startDIal();
		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mHandler.removeCallbacks(runnable);
			runnable=new Runnable() {
				@Override
				public void run() {
					String testmsg = null;
					mBluetoothAdapter.stopLeScan(testmLeScanCallback);
					for (int i = 0; i < list.size(); i++) {
						for (int j = 0; j < getuuid.size(); j++) {
							if (list.get(i).bea_id.equals(getuuid.get(j))) {
								if (testmsg == null) {
									testmsg = "검색된 비콘 리스트\n"
											+ list.get(i).stu_name;
								} else {
									testmsg += "\n" + list.get(i).stu_name;
								}
							}
						}
					}
					endDIal();
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Scanmode_StartScan.this);
					builder.setMessage(testmsg)
							.setCancelable(false)
							.setPositiveButton("확인",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();

				}
			};
			mHandler.postDelayed(runnable, SCAN_PERIOD);

			mBluetoothAdapter.startLeScan(testmLeScanCallback);
		} else {
			mBluetoothAdapter.stopLeScan(testmLeScanCallback);
		}
	}

	private BluetoothAdapter.LeScanCallback testmLeScanCallback = new BluetoothAdapter.LeScanCallback() {
		@Override
		public void onLeScan(final BluetoothDevice device, int rssi,
				byte[] scanRecord) {
			final int rss = rssi;
			final byte[] scan = scanRecord;
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					boolean addcheck = true;
					String uuid = device.getAddress();
					for (int i = 0; i < getuuid.size(); i++) {
						if (getuuid.get(i).equals(uuid)) {
							addcheck = false;
						}
					}
					if (addcheck) {
						getuuid.add(uuid);
					}

				}
			});
		}
	};

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			endDIal();
			// Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG)
			// .show();
			if (firstThread != null) {
				firstThread.interrupt();
			}

			break;
		case FAIR:
			endDIal();

			Toast.makeText(
					this,
					"서버에서 결과값을 얻어오지 못했습니다. 5초후 다시 서버에 통신을 시도합니다."
							+ _message.obj, Toast.LENGTH_SHORT).show();

			break;
		case SUCCESS:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			scanAdapter = new ScanAdapter();
			gridView.setAdapter(scanAdapter);
			if (nowversion) {
				updatebtn.setVisibility(View.INVISIBLE);
			} else {
				updatebtn.setVisibility(View.VISIBLE);
			}
			sc.insert_School("출결체크 스캔 시작", 2);
			scanLeDevice(true);
			
			break;
		case FIRSTSUCCESS:
			if (testscan != null) {
				testscan.setVisibility(View.INVISIBLE);
				testscan.setOnClickListener(null);
				testscan = null;
			}
			if (firstThread == null) {
				firstThread.interrupt();
			}
			Log.i("ddd", "checkscan");
			setList();
			scanAdapter.notifyDataSetChanged();
			Toast.makeText(this, "등원Search" + _message.obj, Toast.LENGTH_SHORT)
					.show();
			if (!nowdate.equals(calendar.get(Calendar.YEAR) + "."
					+ (calendar.get(Calendar.MONTH) + 1) + "."
					+ calendar.get(Calendar.DAY_OF_WEEK))) {
				Log.i("ddd", "noscan");
				log_data.edit().clear().commit();
				setStartData();
			} else {
				if (onoff) {
					Log.i("ddd", "scan");
					scanLeDevice(true);
				}
			}
			break;
		case TWOSUCCESS:
			if (testscan == null) {
				testscan = (TextView) findViewById(R.id.STARTSCAN_TESTSCAN);
				testscan.setVisibility(View.VISIBLE);
				testscan.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						testScanLeDevice(true);
					}
				});
			}
			if (firstThread == null) {
				firstThread.interrupt();
			}
			setList();
			scanAdapter.notifyDataSetChanged();
			Toast.makeText(this, "대기상태", Toast.LENGTH_SHORT).show();
			setCheckMode();
			calendar = Calendar.getInstance();
			if (!nowdate.equals(calendar.get(Calendar.YEAR) + "."
					+ (calendar.get(Calendar.MONTH) + 1) + "."
					+ calendar.get(Calendar.DAY_OF_WEEK))) {
				log_data.edit().clear().commit();
				setStartData();
			} else {
				if (onoff) {

					startThread(checkmode);
				}
			}
			break;
		case THREESUCCESS:
			if (testscan != null) {
				testscan.setVisibility(View.INVISIBLE);
				testscan.setOnClickListener(null);
				testscan = null;
			}
			if (firstThread == null) {
				firstThread.interrupt();
			}
			setList();
			scanAdapter.notifyDataSetChanged();
			Toast.makeText(this, "하원Search" + _message.obj, Toast.LENGTH_SHORT)
					.show();
			if (!nowdate.equals(calendar.get(Calendar.YEAR) + "."
					+ (calendar.get(Calendar.MONTH) + 1) + "."
					+ calendar.get(Calendar.DAY_OF_WEEK))) {
				log_data.edit().clear().commit();
				setStartData();
			} else {
				if (onoff) {
					scanLeDevice(true);
				}
			}
			break;
		}
	}

	private void setCheckMode() {
		int nowtime;
		calendar = Calendar.getInstance();
		nowtime = calendar.get(Calendar.HOUR_OF_DAY) * 100;
		nowtime += calendar.get(Calendar.MINUTE);

		if (settime[0] <= nowtime && nowtime <= settime[1]) {
			if (checkmode != 2) {
				sc.insert_School("등원모드를 시작합니다.", 2);
			}
			checkmode = 2;
			title.setText("등\t원\t체\t크");
			stop.setImageResource(R.drawable.attendschool_in_stop);
		} else if (settime[2] <= nowtime && nowtime <= settime[3]) {
			if (checkmode != 4) {
				sc.insert_School("하원모드를 시작합니다.", 2);
			}
			checkmode = 4;
			title.setText("하\t원\t체\t크");
			stop.setImageResource(R.drawable.attendschool_out_stop);
		} else if (nowtime > settime[3]) {
			Toast.makeText(this, "하원시간이 끝났습니다. 어플을 종료합니다.", Toast.LENGTH_LONG)
					.show();
			onoff = false;
			setList();
			checkback = 1;
			scanLeDevice(false);
			moveTaskToBack(true);

			finish();
		} else {
			if (checkmode != 3) {
				sc.insert_School("대기모드를 시작합니다.", 2);
			}
			checkmode = 3;
			title.setText("대\t기\t상\t태");
		}
	}

	private void mainThread() {
		String msg = "";
		boolean loof = true;
		while (loof) {

			try {

				nowversion = checkVersion();
				JSONObject jsonObject = new JSONObject(publicHttpCallback(
						HTTP_GET_STUDENTLIST,
						"schcode=" + login_code.getString("sch_code", "")));
				if (jsonObject.getBoolean("success")) {
					list = new ArrayList<CheckStudent>();
					try {
						if (!log_data.getString("date", null).equals(date)) {
							msg = jsonObject.getString("payload");
							list.addAll(JsonParser.StartScanMode(msg));

						} else {
							CheckStudent checkStudent;
							for (int i = 0; i < log_data.getInt("size", 0); i++) {
								checkStudent = new CheckStudent();
								checkStudent.stu_code = log_data.getString(
										"stu_code" + i, "");
								checkStudent.stu_name = log_data.getString(
										"stu_name" + i, "");
								checkStudent.stu_cla = log_data.getString(
										"stu_cla" + i, "");
								checkStudent.stu_cla_name = log_data.getString(
										"stu_cla_name" + i, "");
								checkStudent.bea_id = log_data.getString(
										"bea_id" + i, "");
								checkStudent.checkon = log_data.getInt(
										"checkon" + i, 0);
								checkStudent.endkey = log_data.getBoolean(
										"endkey" + i, false);
								list.add(checkStudent);

							}
						}

					} catch (Exception e) {
						Log.i("dd", e.toString());
						msg = jsonObject.getString("payload");
						list.addAll(JsonParser.StartScanMode(msg));
					}
					onNetworkCallback(SUCCESS, "");

					loof = false;
				} else {
					sc.insert_School("원생리스트를 얻지못함(서버or설정 에러)", 3);
					onNetworkCallback(FAIR, jsonObject.getString("message"));

				}
			} catch (Exception e) {
				sc.insert_School("원생리스트를 얻지못함(서버or설정 에러)", 3);
				onNetworkCallback(FAIR, e.toString());
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void firstThread() {
		String msg = "";
		sendlist = new ArrayList<String>();
		scancount++;

		try {
			for (int i = 0; i < alwaysdata.size(); i++) {
				for (int j = 0; j < list.size(); j++) {

					if (list.get(j).bea_id.equals(alwaysdata.get(i))
							&& list.get(j).checkon == 0) {
						sendlist.add(list.get(j).stu_code);
						list.get(j).checkon = 1;
						sc.insert_School(list.get(j).stu_name
								+ "의 비콘이 감지되어 등원처리 되었습니다. " + list.get(j).rssi,
								2);
					}
				}
			}

			for (int i = 0; i < list.size(); i++) {
				list.get(i).nowstate = false;
			}

			for (int i = 0; i < alwaysdata.size(); i++) {
				for (int j = 0; j < list.size(); j++) {
					if (list.get(j).bea_id.equals(alwaysdata.get(i))) {
						list.get(j).nowstate = true;
					}
				}
			}
			if (sendlist.size() > 0) {

				for (int i = 0; i < sendlist.size(); i++) {
					if (codeb == null) {
						codeb = sendlist.get(i);
					} else {
						codeb += "-" + sendlist.get(i);
					}
				}
			}
			Log.i("log", codeb + "d");
			if (isNetworkStat(this)) {
				if (scancount % 5 == 0) {
					if ((savelog = sc.save_School()).getCount() > 0) {
						String logstr = null;
						while (savelog.moveToNext()) {
							if (logstr == null) {
								logstr = savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							} else {
								logstr += "," + savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							}

						}
						JSONObject jsonObjecta = new JSONObject(
								publicHttpCallback(
										HTTP_SEND_LOG,
										"code="
												+ logstr
												+ "&sch="
												+ login_code.getString(
														"sch_code", null)));

						if (jsonObjecta.getBoolean("success")) {
							sc.update_School();

						}
					}
				}

				if (codeb != null) {
					JSONObject jsonObject = new JSONObject(publicHttpCallback(
							HTTP_SEND_START, "code=" + codeb));
					String[] checkon = codeb.split("-");
					for (int i = 0; i < checkon.length; i++) {
						for (int j = 0; j < list.size(); j++) {
							if (list.get(j).stu_code.equals(checkon[i])) {
								sc.insert_School(list.get(j).stu_name
										+ "이 등원처리되어 서버에 전송 및 푸시발송 되었습니다.", 2);
								break;
							}
						}
					}
					codeb = null;
				}
				onNetworkCallback(FIRSTSUCCESS, "");
			} else {
				sc.insert_School("네트워크상태 통신 불가 와이파이연결 안됨", 3);
				onNetworkCallback(FIRSTSUCCESS, "");
			}
		} catch (Exception e) {
			onNetworkCallback(FIRSTSUCCESS, "main" + e.toString());
			sc.insert_School("서버통신오류(서버문제)" + e.toString(), 3);
		}
	}

	private void twoThread() {
		String msg = "";
		scancount++;
		try {
			setList();
			for (int i = 0; i < list.size(); i++) {
				list.get(i).nowstate = false;
			}

			for (int i = 0; i < alwaysdata.size(); i++) {
				for (int j = 0; j < list.size(); j++) {
					if (list.get(j).bea_id.equals(alwaysdata.get(i))) {
						list.get(j).nowstate = true;
					}
				}
			}

			if (isNetworkStat(this)) {

				if (scancount % 5 == 0) {
					if ((savelog = sc.save_School()).getCount() > 0) {
						String logstr = null;
						while (savelog.moveToNext()) {
							if (logstr == null) {
								logstr = savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							} else {
								logstr += "," + savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							}

						}
						JSONObject jsonObjecta = new JSONObject(
								publicHttpCallback(
										HTTP_SEND_LOG,
										"code="
												+ logstr
												+ "&sch="
												+ login_code.getString(
														"sch_code", null)));

						if (jsonObjecta.getBoolean("success")) {
							sc.update_School();

						}
					}
				}
			}

			Thread.sleep(10000);
			onNetworkCallback(TWOSUCCESS, "");
		} catch (Exception e) {
			onNetworkCallback(TWOSUCCESS, "main" + e.toString());
		}
	}

	private void threeThread() {
		scancount++;
		String msg = "";
		String code = null;
		boolean endcheck = true;
		try {
			if (upattend) { // 출결정보 저장
				sc.insert_School("출석정보 갱신시작", 2);

				calendar = Calendar.getInstance();
				String nowday = calendar.get(Calendar.YEAR) + "-"
						+ (calendar.get(Calendar.MONTH) + 1) + "-"
						+ calendar.get(Calendar.DATE);
				for (int i = 0; i < list.size(); i++) {
					if (i == 0) {
						code = list.get(i).stu_cla + "--"
								+ list.get(i).stu_code + "--" + nowday + "--"
								+ (list.get(i).checkon == 0 ? 1 : 0);
					} else {
						code += "-!-" + list.get(i).stu_cla + "--"
								+ list.get(i).stu_code + "--" + nowday + "--"
								+ (list.get(i).checkon == 0 ? 1 : 0);
					}
				}
				if (isNetworkStat(this)) {
					Log.i("dsdf", "dsf0");
					JSONObject jsonObject = new JSONObject(publicHttpCallback(

							HTTP_SEND_CHECK,
							"code=" + code + "&sch="
									+ login_code.getString("sch_code", "")));
					Log.i("dsdf", code);
					if (jsonObject.getBoolean("success")) {
						sc.insert_School("출석정보 갱신성공", 2);
						upattend = false;
					} else {
						sc.insert_School("출석정보 갱신실패(서버및 코드오류)", 3);
					}
				} else {
					sc.insert_School("네트워크상태 통신 불가 와이파이연결 안됨 출석정보 갱신실패", 3);
				}
			}
		} catch (Exception e) {
			sc.insert_School("출석정보 갱신실패" + e.toString(), 3);
		}
		boolean youmu;

		try {

			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).checkon < checklimit) {
					youmu = false;
					for (int j = 0; j < alwaysdata.size(); j++) {
						if (list.get(i).bea_id.equals(alwaysdata.get(j))) {
							youmu = true;
							break;
						}
					}
					if (youmu) {
						if (list.get(i).checkon > 1) {
							sc.insert_School(
									list.get(i).stu_name
											+ "의 비콘의 신호를 다시 인식했습니다."
											+ list.get(i).rssi, 2);
						}
						list.get(i).checkon = 1;
						list.get(i).endkey = true;

					} else if (list.get(i).endkey && !youmu) {
						list.get(i).checkon++;

						if (list.get(i).checkon == checklimit) {
							sc.insert_School(
									list.get(i).stu_name
											+ "의 비콘이 인식되지 않아서 귀가처리됩니다. 마지막rssi값"
											+ list.get(i).rssi, 2);
							if (codea == null) {
								codea = list.get(i).stu_code;
							} else {
								codea += "-" + list.get(i).stu_code;
							}
						} else {
							sc.insert_School(list.get(i).stu_name
									+ "의 비콘이 인식되지 않습니다. 마지막rssi값"
									+ list.get(i).rssi + " "
									+ (checklimit - list.get(i).checkon)
									+ "번 더 인식되지 않으면 귀가처리됩니다.", 2);
						}
					}
				}
			}

			for (int i = 0; i < list.size(); i++) { // 현재비콘상태 초기화
				list.get(i).nowstate = false;
			}

			for (int i = 0; i < alwaysdata.size(); i++) { // 현재 비콘 상태
				for (int j = 0; j < list.size(); j++) {
					if (list.get(j).bea_id.equals(alwaysdata.get(i))) {
						list.get(j).nowstate = true;
					}
				}
			}
			if (isNetworkStat(this)) {

				if (scancount % 5 == 0) {
					if ((savelog = sc.save_School()).getCount() > 0) {
						String logstr = null;
						while (savelog.moveToNext()) {
							if (logstr == null) {
								logstr = savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							} else {
								logstr += "," + savelog.getString(0) + "::"
										+ savelog.getString(1) + "::"
										+ savelog.getString(2);
							}

						}
						JSONObject jsonObjecta = new JSONObject(
								publicHttpCallback(
										HTTP_SEND_LOG,
										"code="
												+ logstr
												+ "&sch="
												+ login_code.getString(
														"sch_code", null)));

						if (jsonObjecta.getBoolean("success")) {
							sc.update_School();

						}
					}
				}

				if (codea != null) {
					JSONObject jsonObject = new JSONObject(publicHttpCallback(
							HTTP_SEND_END, "code=" + codea));

					String[] checkon = codea.split("-");
					for (int i = 0; i < checkon.length; i++) {
						for (int j = 0; j < list.size(); j++) {
							if (list.get(j).stu_code.equals(checkon[i])) {
								sc.insert_School(list.get(j).stu_name
										+ "이 귀가처리되어 서버에 전송 및 푸시발송 되었습니다.", 2);
								break;
							}
						}
					}
					codea = null;
				}
				onNetworkCallback(THREESUCCESS, "");
			} else {
				sc.insert_School("네트워크상태 통신 불가 와이파이연결 안됨", 3);
				onNetworkCallback(THREESUCCESS, "");
			}
		} catch (Exception e) {
			onNetworkCallback(THREESUCCESS, "main" + e.toString());
			sc.insert_School("서버통신오류(서버문제)" + e.toString(), 3);
		}
	}

	public void setList() {
		editor.putString("date", date);
		editor.putInt("size", list.size());
		for (int i = 0; i < list.size(); i++) {
			editor.putString("stu_code" + i, list.get(i).stu_code);
			editor.putString("stu_name" + i, list.get(i).stu_name);
			editor.putString("stu_cla" + i, list.get(i).stu_cla);
			editor.putString("bea_id" + i, list.get(i).bea_id);
			editor.putInt("checkon" + i, list.get(i).checkon);
			editor.putBoolean("endkey" + i, list.get(i).endkey);
		}
		editor.commit();

	}

	class ScanAdapter extends ArrayAdapter<String> {

		public ScanAdapter() {
			super(Scanmode_StartScan.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ScanHolder startHolder;
			final int pos = position;
			if (convertView == null) {
				startHolder = new ScanHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.start_scanmode_row, null);
				int width = ((gridView.getWidth()) / 5);
				int height = ((gridView.getWidth()) / 5);
				startHolder.ll = (LinearLayout) convertView
						.findViewById(R.id.START_SCANMODE_LL);
				startHolder.ll.setLayoutParams(new LinearLayout.LayoutParams(
						width, height));

				startHolder.textView = (TextView) convertView
						.findViewById(R.id.START_SCANMODE_ROW);
				convertView.setTag(startHolder);
			} else {
				startHolder = (ScanHolder) convertView.getTag();
			}
			if (list.get(position).stu_name.equals("null")
					|| list.get(position).stu_name.equals("")) {
				startHolder.textView.setText("이름없음");
			} else if (list.get(position).bea_id.equals("null")
					|| list.get(position).equals("")) {
				startHolder.textView.setText(list.get(position).stu_name
						+ "\n비콘미배정");
			} else {
				startHolder.textView.setText(list.get(position).stu_name);
			}
			if (checkmode == 3) {
				if (list.get(position).nowstate) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_green_on);
				} else {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_off);
				}
			} else if(checkmode==2){
				if (list.get(position).checkon == 0) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_off);
				} else if (list.get(position).checkon >= 1
						&& list.get(position).checkon < checklimit) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_on);
					startHolder.textView.setText(startHolder.textView.getText()
							+ "\n등원됨");
				} else if (list.get(position).checkon == checklimit) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_off);
					startHolder.textView.setText(startHolder.textView.getText()
							+ "\n하원됨");
				}
			} else if(checkmode==4){
				if (list.get(position).checkon == 0) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_off);
				} else if (list.get(position).checkon >= 1
						&& list.get(position).checkon < checklimit) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_off);
					startHolder.textView.setText(startHolder.textView.getText()
							+ "\n등원됨");
				} else if (list.get(position).checkon == checklimit) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_yellow_on);
					startHolder.textView.setText(startHolder.textView.getText()
							+ "\n하원됨");
				}
			} else {
				if (list.get(position).checkon == 0) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_off);
				} else if (list.get(position).checkon >= 1
						&& list.get(position).checkon < checklimit) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_blue_on);
					startHolder.textView.setText(startHolder.textView.getText()
							+ "\n등원됨");
				} else if (list.get(position).checkon == checklimit) {
					startHolder.ll
							.setBackgroundResource(R.drawable.selectitem_yellow_on);
					startHolder.textView.setText(startHolder.textView.getText()
							+ "\n하원됨");
				}
			}

			if (list.get(position).nowstate) {
				startHolder.textView.setText(startHolder.textView.getText()
						+ "\n" + list.get(pos).bea_id + "\n비콘인식됨\n"
						+ list.get(pos).rssi);
			} else {
				startHolder.textView.setText(startHolder.textView.getText()
						+ "\n" + list.get(pos).bea_id + "\n비콘인식안됨\n"
						+ list.get(pos).rssi);
			}

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder builder = new AlertDialog.Builder(
							Scanmode_StartScan.this);
					builder.setMessage(
							list.get(pos).stu_name + "어린이 의 등하원 상태를 확인해주세요")
							.setCancelable(true)
							.setPositiveButton("하원",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {

											AlertDialog.Builder builder = new AlertDialog.Builder(
													Scanmode_StartScan.this);
											builder.setMessage(
													list.get(pos).stu_name
															+ "어린이의 하원을 선택하였습니다\n 확인을 누르시면 부모님께 메세지가 전송됩니다.")
													.setCancelable(true)
													.setPositiveButton(
															"확인",
															new DialogInterface.OnClickListener() {
																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	subThread(
																			2,
																			list.get(pos).stu_code);
																	list.get(pos).checkon = checklimit;
																	list.get(pos).endkey = true;
																	scanAdapter
																			.notifyDataSetChanged();
																}
															})
													.setNegativeButton(
															"종료",
															new DialogInterface.OnClickListener() {
																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	dialog.dismiss();
																}
															});
											AlertDialog alert = builder
													.create();
											alert.show();
										}
									})
							.setNegativeButton("등원",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {

											AlertDialog.Builder builder = new AlertDialog.Builder(
													Scanmode_StartScan.this);
											builder.setMessage(
													list.get(pos).stu_name
															+ "어린이의 등원을 선택하였습니다\n 확인을 누르시면 부모님께 메세지가 전송됩니다.")
													.setCancelable(true)
													.setPositiveButton(
															"확인",
															new DialogInterface.OnClickListener() {
																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	subThread(
																			1,
																			list.get(pos).stu_code);
																	list.get(pos).checkon = 1;
																	list.get(pos).endkey = false;
																	scanAdapter
																			.notifyDataSetChanged();
																}
															})
													.setNegativeButton(
															"종료",
															new DialogInterface.OnClickListener() {
																@Override
																public void onClick(
																		DialogInterface dialog,
																		int which) {
																	dialog.dismiss();
																}
															});
											AlertDialog alert = builder
													.create();
											alert.show();

										}
									});
					AlertDialog alert = builder.create();
					alert.show();

				}
			});

			return convertView;
		}
	}

	class ScanHolder {
		TextView textView;
		LinearLayout ll;
	}

	private boolean checkVersion() {

		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_VERSION, ""));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				msg = new JSONObject(msg).getString("Waukidsschool");
				msg = msg.replace("d", ".");

				Log.i("ddd", msg + " " + getVersion());
				if (Double.parseDouble(msg) > Double.parseDouble(getVersion())) { // 학원정보저장.
					return false;
				} else {
					return true;
				}

			}
		} catch (Exception e) {
		}
		;
		return true;
	}

	private String getVersion() { // 매니페스트 버전이름 들고옴.
		PackageInfo pi = null;
		try {
			pi = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return pi.versionName;
	}

	class LogAdapter extends ArrayAdapter<String> {

		public LogAdapter() {
			super(Scanmode_StartScan.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return loglist.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			TextView tv;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.logitem,
						null);
				tv = (TextView) convertView.findViewById(R.id.logitem_tv);
				convertView.setTag(tv);
			} else {
				tv = (TextView) convertView.getTag();
			}
			tv.setText(loglist.get(position));
			return convertView;
		}

	}
}
